package com.qf.shop.dao.Impl;

import com.qf.shop.dao.AddressDao;
import com.qf.shop.entity.Address;
import com.qf.shop.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public List<Address> selectAll(int uid) {
        try {//--------------------------------------------------------------------------默认地址是level 是1， 其他地址是0，所以降序会将 默认地址放到第一位
            return queryRunner.query(DruidUtils.getConnection(), "select * from address where uid = ? order by level desc;", new BeanListHandler<>(Address.class), uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int insert(Address address) {
        Object[] params = {address.getDetail(), address.getName(), address.getPhone(), address.getUid(), address.getLevel()};
        try {
            return queryRunner.update(DruidUtils.getConnection(), "insert into address(detail,name,phone,uid,level) values(?,?,?,?,?);", params);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public int update(Address address) {
        Object[] params = {address.getName(), address.getDetail(), address.getPhone(), address.getId()};
        try {//                                                       sql语句，注意一个逗号问题
            return queryRunner.update(DruidUtils.getConnection(),"update address set name = ?,detail = ?,phone = ? where id = ?;",params);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

        @Override
        public int delete ( int id){
            try {
                return queryRunner.update(DruidUtils.getConnection(),"delete from address where id= ?;",id);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return 0;
        }

        @Override
        public int updateDefault ( int id){
            try {
                return queryRunner.update(DruidUtils.getConnection(),"update address set level = 1 where id =?; ",id);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return 0;
        }

        @Override
        public int updateCommns ( int id, int uid){
            try {
                return queryRunner.update(DruidUtils.getConnection(),"update address set level = 0 where id != ? and uid = ? ;",id,uid);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return 0;
        }
    }
